<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" >
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="queryParams.eventType" placeholder="请选择事件类型" clearable size="small">
          <el-option
            v-for="dict in eventTypeOptions"
            :key="dict.eventType"
            :label="dict.eventTypeName"
            :value="dict.eventType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事件项" prop="eventItemCode">
        <el-input
          v-model="queryParams.eventItemCode"
          placeholder="请输入事件项"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事件项名称" prop="eventItemName" label-width="90px">
        <el-input
          v-model="queryParams.eventItemName"
          placeholder="请输入事件项名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['config:item:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['config:item:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['config:item:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleExport"
          v-hasPermi="['config:item:export']"
        >导出</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="itemList"
              :default-sort = "{prop: 'eventItemCode', order: 'ascending'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="属性名" align="center" prop="eventItemCode" sortable>
        <template slot-scope="scope">
          <a href="#" style="cursor: pointer;color: #007aff;" @click="handelDetail(scope.row)">{{scope.row.eventItemCode}}</a>
        </template>
      </el-table-column>
      <el-table-column label="属性显示名称" align="center" prop="eventItemName" />
      <el-table-column label="属性分类" align="center" prop="eventType" :formatter="eventTypeFormat" />
      <el-table-column label="值类型" align="center" prop="valueType"  :formatter="valueFormat" />
      <el-table-column label="可用此属性的事件要求" align="center" prop="remark"   />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:item:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:item:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改事件项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" v-if="open" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="事件类型" prop="eventId">
          <el-select v-model="form.eventId" placeholder="请选择事件类型">
            <el-option
              v-for="dict in eventTypeOptions"
              :key="dict.id"
              :label="dict.eventTypeName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件项编码" prop="eventItemCode">
          <el-input v-model="form.eventItemCode" placeholder="请输入事件项编码" />
        </el-form-item>
        <el-form-item label="事件项名称" prop="eventItemName">
          <el-input v-model="form.eventItemName" placeholder="请输入事件项名称" />
        </el-form-item>
        <el-form-item label="事件取值类型" prop="valueType">
          <el-select v-model="form.valueType" placeholder="请选择事件值类型">
            <el-option
              v-for="dict in valueTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件函数"  prop="eventMethod">
          <el-select v-model="form.eventMethod" multiple placeholder="请选择事件函数(多选)">
            <el-option
              v-for="dict in emethodOptions"
              :key="dict.id"
              :label="dict.methodName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <div style="padding-left:20px;padding-right:20px;padding-bottom:10px;font-size:12px;color:#8492a6;">虚拟属性中涉及的事件属性，如果被影藏了，次虚拟属性依然生效可被使用，如果是自定义维度表，创建虚拟属性的SQL表达式，格式必须是跑【dimensions自定义维度表表名，维度表内属性】</div>
        <el-form-item label="SQL表达式" prop="itemExpression">
          <el-input type="textarea" v-model="form.itemExpression" placeholder="请输入SQL表达式" />
        </el-form-item>
        <el-form-item label="可用此属性的事件要求" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入可用此属性的事件要求" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-drawer
      title="虚拟属性详情"
      :visible.sync="detailOpen"
      size="50%">
      <div style="padding:20px;">
        <el-form ref="eventPropertyInfo" :model="eventPropertyInfo"  label-width="180px" label-position="left">
          <el-form-item label="属性类型">
             <label>{{eventPropertyInfo.eventType}}</label>
          </el-form-item>
          <el-form-item label="属性显示名称" prop="eventItemName">
            <label>{{eventPropertyInfo.eventItemName}}</label>
          </el-form-item>
          <el-form-item label="属性名" prop="eventItemCode">
            <label>{{eventPropertyInfo.eventItemCode}}</label>
          </el-form-item>

          <el-form-item label="事件取值类型" prop="ValueType">
            <label>{{eventPropertyInfo.valueType}}</label>
          </el-form-item>
          <el-form-item label="事件函数"  prop="ValueType">
            <label>{{eventPropertyInfo.eventMethod}}</label>
          </el-form-item>
          <div style="padding-left:20px;padding-right:20px;padding-bottom:10px;font-size:12px;color:#8492a6;">虚拟属性中涉及的事件属性，如果被影藏了，次虚拟属性依然生效可被使用，如果是自定义维度表，创建虚拟属性的SQL表达式，格式必须是跑【dimensions自定义维度表表名，维度表内属性】</div>
          <el-form-item label="SQL表达式" prop="itemExpression">
            <label>{{eventPropertyInfo.itemExpression}}</label>
          </el-form-item>
          <el-form-item label="可用此属性的事件要求" prop="remark">
            <label>{{eventPropertyInfo.remark}}</label>
          </el-form-item>
          <el-divider></el-divider>
          <h4>关联此属性的事件明细</h4>
          <el-table v-loading="loading" :data="relaEventList">
            <el-table-column label="事件显示名称" align="center" prop="eventTypeName" />
            <el-table-column label="事件名" align="center" prop="eventType"  />
            <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
          </el-table>

          <pagination
            v-show="relaTotal>0"
            :total="relaTotal"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getRelaEventList"
          />
        </el-form>
        <div slot="footer" class="dialog-footer" style="float:right;margin-top:20px;">
          <el-button @click="detailCancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {listItem, getItem, delItem, addItem, updateItem, exportItem, eventTypeOptions} from "@/api/config/item";
import {getEventMethodOptions} from "@/api/config/emethod";
import {listType} from "@/api/config/type";
export default {
  name: "virtualitem",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 事件项目表格数据
      selectName:null,
      itemList: [],
      relaEventList: [],
      relaTotal:0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailOpen: false,
      // 事件类型字典
      eventTypeOptions: [],
      valueTypeOptions: [],
      emethodOptions:[],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventType:[],
        eventItemCode: undefined,
        eventItemName: undefined,
        status: undefined
      },
      // 表单参数
      eventPropertyInfo:{},
      form: {
        id: undefined,
        eventId: undefined,
        eventItemCode: undefined,
        eventItemName: undefined,
        eventMethod:undefined,
        remark:undefined,
        status: undefined
      },
      // 表单校验
      rules: {
        eventId: [
          { required: true, message: "请选择事件类型", trigger: "blur" }
        ],
        eventItemCode: [
          { required: true, message: "请填写事件项编码", trigger: "blur" }
        ],
        eventItemName: [
          { required: true, message: "请填写事件项名称", trigger: "blur" }
        ],
        ValueType: [
          { required: true, message: "请选择值类型", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getEventTypeList();
    this.getMethodList();
    this.getDicts("sys_value_type").then(response => {
      this.valueTypeOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询事件项目列表 */
    getList() {
      this.loading = true;
      this.queryParams.categoryType='virtual';
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getEventTypeList(){
      var param={status:'Y'};
      eventTypeOptions(param).then(response => {
        this.eventTypeOptions = response.data;
      });
    },

    getMethodList(){
      var param={status:'Y'};
      getEventMethodOptions(param).then(response => {
        this.emethodOptions = response.data;
      });
    },

    // 事件类型字典翻译
    eventTypeFormat(row, column) {
      var eventTypeName='';
      for(var i=0;i<this.eventTypeOptions.length;i++){
        if(this.eventTypeOptions[i].eventType==row.eventType){
          eventTypeName=this.eventTypeOptions[i].eventTypeName;
          break;
        }
      }
      return eventTypeName;
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },

    valueFormat(row, column) {
      return this.selectDictLabel(this.valueTypeOptions, row.valueType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    handelDetail(row) {
      this.detailOpen = true;
      const id = row.id;
      this.selectName=row.eventItemCode;
      getItem(id).then(response => {
        this.eventPropertyInfo = response.data;
        if(response.data.eventMethod){
          var ary=response.data.eventMethod.split(',');
          var emethod=[];
          for(var j=0;j<ary.length;j++){
            emethod.push(parseInt(ary[j]));
          }
          this.eventPropertyInfo.eventMethod=emethod;
        }
      });
      this.getRelaEventList();
    },

    getRelaEventList() {
      this.loading = true;
      this.queryParams.categoryType='virtual';
      this.queryParams.eventJson=this.selectName;
      listType(this.queryParams).then(response => {
        this.relaEventList = response.rows;
        this.relaTotal = response.total;
        this.loading = false;
      });
    },

    detailCancel() {
      this.detailOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        eventId: undefined,
        eventItemCode: undefined,
        eventItemName: undefined,
        eventMethod:undefined,
        itemExpression:undefined,
        remark:undefined,
        categoryType:'virtual',
        status: 'Y'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加事件项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data;
        if(response.data.eventMethod){
          var ary=response.data.eventMethod.split(',');
          var emethod=[];
          for(var j=0;j<ary.length;j++){
            emethod.push(parseInt(ary[j]));
          }
          this.form.eventMethod=emethod;
        }
        this.open = true;
        this.title = "修改事件项目";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        let methodAry= this.form.eventMethod;
        if(this.form.eventMethod){
          this.form.eventMethod=methodAry.join(",");
        }
        let eventId=this.form.eventId;
        let event=this.eventTypeOptions.find(etype=>etype.id===eventId);
        if(event){
          this.form.eventType=event.eventType;
        }
        if (valid) {
          if (this.form.id != undefined) {
            updateItem(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.form.categoryType='virtual';
            addItem(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除事件项目编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delItem(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有事件项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportItem(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
